package baiqitun.stupro.common.util;

import baiqitun.stupro.common.exception.enums.support.StuproExceptionEnum;
import baiqitun.stupro.common.exception.StuproException;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 文件上传工具类
 * @author kedaji
 */
public class UploadUtil {
    /**
     * 单文件上传
     * @param request HTTP请求
     */
    public static MultipartFile single(HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("file");
        if (multipartFile == null){
            throw new StuproException(StuproExceptionEnum.PARAMETER_CANNOT_NULL).put("文件", null);
        }
        return multipartFile;
    }
    /**
     * 多文件上传
     * @param request HTTP请求
     */
    public static List<MultipartFile> multiple(HttpServletRequest request){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultiValueMap<String, MultipartFile> multiFileMap = multipartRequest.getMultiFileMap();
        List<MultipartFile> fileList = null;
        for (Map.Entry<String, List<MultipartFile>> entry: multiFileMap.entrySet()){
            fileList = entry.getValue();
        }
        return fileList;
    }
}
